import numpy as np
import os
import cv2
os.chdir(os.path.dirname(__file__))
import csv
from tkinter import filedialog
# 定义提取参数
offset = 19   
length = 8192
# 定义图像尺寸
img_height = 268
img_width  = 268 
# ---------  整幅图读取 ---------
def get_raw(path):
    
    raw = np.fromfile(path, dtype=np.uint8)
    return raw
# 递归列出
# def list_all_files_with_dir(root_folder):
#     result = []
#     for dirpath, dirnames, filenames in os.walk(root_folder):
#         for filename in filenames:
#             full_path = os.path.join(dirpath, filename)
#             result.append({
#                 'file_path': full_path,
#                 'directory': dirpath
#             })
#     return result

def convert_to_u16_image_advanced(data_1d, height, width, byte_order='little'):
    """
    增强版转换函数，支持字节序处理
    
    参数:
        data_1d: 一维uint8数组
        height: 目标图像高度
        width: 目标图像宽度
        byte_order: 字节序 ('little' 或 'big')
    """
    required_bytes = height * width * 2
    
    # 处理数据长度
    if len(data_1d) < required_bytes:
        print(f"警告: 数据不足，需要{required_bytes}字节，实际{len(data_1d)}字节")
        padded_data = np.zeros(required_bytes, dtype=np.uint8)
        padded_data[:len(data_1d)] = data_1d
        data_1d = padded_data
    elif len(data_1d) > required_bytes:
        print(f"信息: 数据过多，截断前{required_bytes}字节")
        data_1d = data_1d[:required_bytes]
    
    # 处理字节序
    if byte_order == 'big':
        # 大端序: 交换每两个字节的顺序
        data_1d_swapped = data_1d.copy()
        data_1d_swapped[0::2] = data_1d[1::2]  # 偶数索引位置放原奇数位置的数据
        data_1d_swapped[1::2] = data_1d[0::2]  # 奇数索引位置放原偶数位置的数据
        data_1d = data_1d_swapped
    
    # 转换为u16并重塑
    u16_data = data_1d.view(np.uint16)
    img_2d = u16_data.reshape(height, width)
    
    return img_2d

def list_all_files_with_dir(directory, extension='.bin'):
    """列出目录下所有指定扩展名的文件，包括路径，并按数字排序（如果文件名中有数字）"""
    files = [os.path.join(directory, f) for f in os.listdir(directory) if f.endswith(extension)]
    # 按数字排序：提取文件名中的数字部分（去掉扩展名，然后提取连续的数字）
    files.sort(key=lambda x: int(''.join(filter(str.isdigit, os.path.basename(x)))))
    return files

def save_image_to_file(image, filename):
    with open(filename, 'wb') as file:
        # 将整个图像数组以二进制形式写入文件
        file.write(image.tobytes())

if __name__ == '__main__':

    directory  = filedialog.askdirectory(title="请选择文件夹")
    file_paths = list_all_files_with_dir(directory)
        # 初始化img_1d
    img_1d = np.array([], dtype=np.uint8)
    print(file_paths)
    for path in file_paths :
        raw=get_raw(path)
        print(raw.size)
        raw=raw[offset:offset+length]
        img_1d = np.concatenate((img_1d, raw))
        print(img_1d.size)
    img=convert_to_u16_image_advanced(img_1d,img_height,img_width,'little')
    save_image_to_file(img,"data.raw")    

